package com.chenqq.qsocket.handler;

import com.chenqq.qsocket.listener.SocketMessageListener;
import com.chenqq.qsocket.message.FileTask;
import com.chenqq.qsocket.message.ReceiveFileFinishMessage;
import com.chenqq.qsocket.message.SocketMessage;
import com.chenqq.qsocket.tools.FileUtil;
import com.chenqq.qsocket.tools.LogShow;

import org.apache.mina.core.session.IoSession;
import org.json.JSONException;

import java.net.SocketAddress;


public class ReceiveFileFinishMessageHandler extends FileMessageHandler {

	@Override
	public void handleMessage(SocketMessage msg, IoSession session) throws JSONException {
		ReceiveFileFinishMessage receiveFileMessage = new ReceiveFileFinishMessage(
				msg);
		ReceiveFileFinishMessage.ReceiveFileInfo receiveFileInfo = receiveFileMessage
				.getReceiveFileInfo();
		SocketAddress remoteAddress = session.getRemoteAddress();
		String replace = remoteAddress.toString().replace("/", "");
		String[] split = replace.split(":");
		FileTask fileTask = mFileTasks.get(receiveFileInfo.id);
		if (fileTask == null) {
			LogShow.showV("wrong file task id " + receiveFileInfo.id);
			session.closeNow();
		} else {
			if(receiveFileInfo.success){
				LogShow.showV("对方接收并校验成功，总计用时(压缩+发送文件+解压):"+(System.currentTimeMillis()-fileTask.startTime)/1000d+" s");
				if (socketMessageListener!=null){
					socketMessageListener.showFileInfo(tag,"对方接收并校验成功，总计用时(压缩+发送文件+解压):"+(System.currentTimeMillis()-fileTask.startTime)/1000d+" s");
					socketMessageListener.sendMessageSuccess(tag);
				}
			}else{
				LogShow.showV("对方并未校验成功");
				if (socketMessageListener!=null){
					socketMessageListener.sendMessageFail(""+receiveFileInfo.id,"对方并未校验成功");
				}
			}
			removeFileTask(receiveFileInfo.id,false);
			if (fileTask.isZipped)
			FileUtil.deleteFile(fileTask.zippedFilePath);
		}

	}



}
